import { Scene } from './Scene';
import { Camera } from './Camera';
import { Input } from './input/Input';

export class Stage {
  private canvas: HTMLCanvasElement;
  private context: CanvasRenderingContext2D;
  private camera: Camera;
  private input: Input;
  private currentScene: Scene | null = null;
  private lastTime: number = 0;
  private animationFrameId: number | null = null;

  constructor(canvas: HTMLCanvasElement) {
    this.canvas = canvas;
    const ctx = canvas.getContext('2d');
    if (!ctx) throw new Error('Could not get 2D context');
    this.context = ctx;
    
    this.camera = new Camera(canvas.width, canvas.height);
    this.input = new Input(canvas);
    window.addEventListener('resize', () => this.handleResize());
  }

  setScene(scene: Scene): void {
    this.currentScene = scene;
  }

  start(): void {
    this.lastTime = performance.now();
    this.loop();
  }

  stop(): void {
    if (this.animationFrameId) {
      cancelAnimationFrame(this.animationFrameId);
      this.animationFrameId = null;
    }
    this.input.destroy();
  }

  private loop(): void {
    const now = performance.now();
    const deltaTime = (now - this.lastTime) / 1000;
    this.lastTime = now;

    // Clear canvas
    this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);

    // Update and render scene
    if (this.currentScene) {
      this.context.save();
      this.camera.applyTransform(this.context);
      this.currentScene.update(deltaTime);
      this.currentScene.render(this.context, this.camera);
      this.context.restore();
    }

    this.animationFrameId = requestAnimationFrame(() => this.loop());
  }

  private handleResize(): void {
    this.canvas.width = window.innerWidth;
    this.canvas.height = window.innerHeight;
    this.camera.width = this.canvas.width;
    this.camera.height = this.canvas.height;
  }
}
